package cn.jdemo.ref.PhantomReference;

import java.lang.ref.PhantomReference;
import java.lang.ref.ReferenceQueue;

public class App {
    public static void main(String[] args) throws InterruptedException {
        test01();
        test02();
    }

    /**
     * 输出:（从队列中可知，obj被回收了）
     * java.lang.ref.PhantomReference@5680a178
     *
     */
    private static void test01() throws InterruptedException {
        Object obj = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> phantomReference = new PhantomReference<Object>(obj,referenceQueue);

        obj = null;
        System.gc();

        System.out.println(referenceQueue.remove());
    }

    /**
     * 输出:
     * null
     *
     */
    private static void test02() {
        Object obj = new Object();
        ReferenceQueue<Object> referenceQueue = new ReferenceQueue<>();
        PhantomReference<Object> phantomReference = new PhantomReference<Object>(obj,referenceQueue);
        obj = null;
        // System.gc();
        System.out.println(referenceQueue.poll());
    }


}
